package com.changgou.page.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.changgou.entity.Result;
import com.changgou.feign.CategoryFeign;
import com.changgou.feign.SpuFeign;
import com.changgou.page.service.PageService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @Author: 少迪
* @Date: Created in 2019-08-09 11:05
* @Description:
* @Version: 1.0
*/

@Service
public class PageServiceImpl implements PageService {

    @Autowired
    private TemplateEngine templateEngine;

    @Value( "${page.path}" )
    private String path;

    @Value( "${domain.cart}" )
    private String cartDomain;

    @Autowired
    private SpuFeign spuFeign;

    @Autowired
    private CategoryFeign categoryFeign;

    @Override
    public void createPage(String spuId) {

        //{ flag:true,code:20000,message:"",data:{ spu:{} ,skuList:[] } }
        Result goodsResult = spuFeign.findById( spuId );
        Map goods=  (Map)goodsResult.getData();
        //spu对象
        Map spu= (Map) goods.get( "spu" );
        //sku列表
        List<Map> skuList= (List<Map>) goods.get( "skuList" );
        //商品分类
        List categoryList = getCategoryList( spu );
        spu.put("categoryList" ,categoryList );

        //spu图片列表
        String[] images = ((String) spu.get( "images" )).split( "," );
        spu.put( "images", images);

        //参数处理
        if(Strings.isEmpty((String)spu.get( "paraItems" ) ) ){
            spu.put( "paraItems","{}" );
        }
        Map paraItems = JSON.parseObject( (String) spu.get( "paraItems" ) );
        spu.put( "paraItems",paraItems );

        //规格选项列表处理
        if(Strings.isEmpty( (String) spu.get( "specItems" )  )){
            spu.put( "specItems","{}" );
        }
        Map<String,List<String>> specItems = JSON.parseObject( (String) spu.get( "specItems" ),Map.class );
        spu.put( "specItems",specItems );


        //key: 规格json字符串   value:页面名称
        Map<String,String> urlMap=new HashMap(100);
        for(Map sku:skuList){
            if(Strings.isEmpty( (String) sku.get( "spec" ) ) ){
                sku.put( "spec","{}" );
            }
            Map spec = JSON.parseObject( (String) sku.get( "spec" ) );
            sku.put( "spec",spec );

            String specJson = JSON.toJSONString( spec , SerializerFeature.MapSortField);
            urlMap.put(specJson, sku.get( "id" )+".html" );

            //循环规格选项 ，以当前sku的规格选项为基准，得到更改后的规格json
            Map skuSpec=new HashMap(100);
            //key 规格名称
            for( String key:specItems.keySet()  ){
                //option 规格选项
                for( String option: specItems.get( key )   ){
                    //得到当前sku的规格map
                    //深克隆
                    Map spec2 = JSON.parseObject( JSON.toJSONString( spec ) );
                    spec2.put( key,option );
                    skuSpec.put( key+":"+option,  JSON.toJSONString(spec2 ,SerializerFeature.MapSortField ) );
                }
            }
            sku.put( "skuSpec",skuSpec );
            System.out.println(sku.get( "id" )+"  skuSpec："+  skuSpec);
        }
        spu.put( "urlMap",urlMap );

        System.out.println("urlMap："+  urlMap);


        for(Map sku:skuList){
            //sku图片列表
            String[] skuImages = ((String) sku.get( "images" )).split( "," );
            sku.put( "images", skuImages);

            Context context=new Context(  );
            Map dataModel=new HashMap(100);
            dataModel.put( "spu", spu);
            dataModel.put( "sku", sku );
            dataModel.put( "cartDomain",cartDomain );
            context.setVariables( dataModel );
            try {
                File file=new File( path+ sku.get( "id" ) +".html" );
                PrintWriter writer=new PrintWriter( file,"utf-8" );
                templateEngine.process( "item", context,writer);
                writer.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 获取商品分类列表
     * @param spu
     * @return
     */
    private List getCategoryList(Map spu){

        Integer  category1Id = (Integer)spu.get( "category1Id" );
        Integer  category2Id = (Integer)spu.get( "category2Id" );
        Integer  category3Id = (Integer)spu.get( "category3Id" );

        Result categoryResult1 = categoryFeign.findById( category1Id );
        Result categoryResult2 = categoryFeign.findById( category2Id );
        Result categoryResult3 = categoryFeign.findById( category3Id );

        Map category1 = (Map)categoryResult1.getData();
        Map category2 = (Map)categoryResult2.getData();
        Map category3 = (Map)categoryResult3.getData();

        String category1Name = (String)category1.get( "name" );
        String category2Name = (String)category2.get( "name" );
        String category3Name = (String)category3.get( "name" );

        List categoryList=new ArrayList(  );
        categoryList.add( category1Name );
        categoryList.add( category2Name );
        categoryList.add( category3Name );
        return categoryList;

    }

}
